/**
 * Verifications.java
 * @author: liuex
 * 2007-12-27 ����09:56:40
 *
 * note: 
 */
package lex.proxyverfier.prefs;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.table.AbstractTableModel;

import org.lex.utils.text.Splitter;


public class Verifications extends AbstractTableModel
{
	private static final String[] COLUMN_NAMES = { "URL" };
	private ArrayList<URL> list = null;

	public static String encode( Verifications v )
	{
		if( v.list.isEmpty() )
			return "";
		StringBuilder buf = new StringBuilder();
		Iterator<URL> iter = v.list.iterator();
		while( true )
		{
			buf.append( iter.next().toString() );
			if( iter.hasNext() )
				buf.append( ',' );
			else
				break;
		}
		return buf.toString();
	}

	public static Verifications decode( String urls )
	{
		Verifications v = new Verifications();
		if( null != urls && false == urls.isEmpty() )
		{
			String[] tokens = Splitter.CommaSplitter.split( urls );
			for( int i = 0; i < tokens.length; i++ )
				v.addURL( tokens[i] );
		}
		return v;
	}

	private Verifications()
	{
		this.list = new ArrayList<URL>();
	}

	/**
	 * line := host<space>port
	 * 
	 * @param url
	 */
	public void addURL( String url )
	{
		if( null == url )
			return;
		url = url.trim();
		if( 0 == url.length() )
			return;
		URL url0 = null;
		try
		{
			url0 = new URL( url );
		}
		catch( MalformedURLException e )
		{
			e.printStackTrace();
		}
		if( null != url0 )
		{
			this.list.add( url0 );
			this.fireTableDataChanged();
		}
	}

	public URL[] getAllURLs()
	{
		return this.list.toArray( new URL[this.list.size()] );
	}

	public URL getURL( int row )
	{
		return this.list.get( row );
	}

	public void remove( int row )
	{
		this.list.remove( row );
		this.fireTableDataChanged();
	}

	@Override
	public String getColumnName( int column )
	{
		return COLUMN_NAMES[column];
	}

	@Override
	public Class<?> getColumnClass( int column )
	{
		switch( column )
		{
		case 0:
			return URL.class;
		default:
			return Object.class;
		}
	}

	public int getColumnCount()
	{
		return COLUMN_NAMES.length;
	}

	@Override
	public int getRowCount()
	{
		return list.size();
	}

	@Override
	public Object getValueAt( int row, int column )
	{
		return list.get( row );
	}

	@Override
	public String toString()
	{
		return encode( this );
	}
}
